import requests
from bs4 import BeautifulSoup
import openpyxl
from pyecharts.charts import Bar,Line  # 官方已取消 pyecharts.Bar 方式导入
from pyecharts import options
from pyecharts.globals import ThemeType
from datetime import datetime
from pyecharts.datasets import register_files

# 获取双色球中奖号码信息
def get_data(n):
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE'
    }
    url = 'https://chart.cp.360.cn/kaijiang/ssq?lotId=220051&chartType=undefined&spanType=0&span={}'.format(n)  # 爬取期数
    respons = requests.get(url,headers=headers)
    text = respons.text
    soup = BeautifulSoup(text,'lxml')
    tbody = soup.find_all('thead',class_="kaijiang")[0]
    tbody_th = tbody.find_all('th')
    # 创建一个excel文件
    wb = openpyxl.Workbook()  # 新建excel文件
    wb.encoding='utf_8_sig'
    ws = wb.active  # 激活sheet，用于后续将数据写入
    ws.title = '双色球中奖信息'  # 指定sheet的名称


    # 将“表头”写入excel中
    ws.cell(row=1,column=1,value=list(tbody_th[0].stripped_strings)[0])  # cell 方法给excel写入数据，row= 行，column=列，value=要写入的值
    ws.cell(row=1,column=2,value=list(tbody_th[1].stripped_strings)[0])
    ws.cell(row=1,column=3,value=list(tbody_th[-6].stripped_strings)[0])
    ws.cell(row=1,column=4,value=list(tbody_th[-5].stripped_strings)[0])

    tbody = soup.find_all('tbody',id="data-tab")[0]
    trs = tbody.find_all('tr')
    data_list=[] # 要写入excel的数据
    red_list = [] # 红球
    blue_list = [] # 蓝球
    for tr in trs:
        tds = tr.find_all('td')[:4]
        blue_list.append(list(tds[3].stripped_strings)[0])  # 获取蓝球号码
        tds_text = [] # 中奖号码信息
        redBall = ''
        for index,td in enumerate(tds):
            if index == 2:  # 红球
                for i in list(td.stripped_strings):
                    redBall = redBall+' '+ i
                    red_list.append(i)
                tds_text.append(redBall.lstrip())
            else:
                tds_text.append(list(td.stripped_strings)[0])
        data_list.append(tds_text)
    for i,dl in enumerate(data_list):
        for j,dt in enumerate(dl):
            ws.cell(row=i+2,column=j+1,value=dt) # 将中奖号码信息写入excel中
    wb.save('双色球中奖信息.xlsx')  # 将数据保存到本地excel中
    return red_list,blue_list

# 获取球出现的次数
def count_ball(ball_list,color_list):
    '''
    :param ball_list: 所有中奖号码，红球+蓝球 剔重数据
    :param color_list: 红球号码或蓝球号码
    :return: 中奖号码出现的次数
    '''
    ball_dict={}
    for d in ball_list:
        ball_dict[d]=0
    for ball in ball_list:
        ball_dict[ball]=color_list.count(ball)  # 获取球出现的次数
    count_y = list(ball_dict.values())
    return count_y

# 柱状图
def mkCharts(x,y1,y2,n):
    bar = Bar(init_opts = options.InitOpts(theme=ThemeType.DARK))  # 对表格添加主题
    bar.add_xaxis(x)  # x轴：所有中奖号码，红球+蓝球
    bar.add_yaxis('红球',y1)
    bar.add_yaxis('蓝球', y2)
    tim = datetime.now().strftime('%Y-%m-%d')
    bar.set_global_opts(title_opts=options.TitleOpts(title="最近{}期双色球红蓝球中奖次数".format(n), subtitle=tim))
    bar.render('双色球(柱状图).html')

# 折线图，使用官方主题 https://pyecharts.org/#/zh-cn/themes?id=%e4%b8%bb%e9%a2%98%e9%a3%8e%e6%a0%bc
def mkLine1(x,y1,y2,n):
    tim = datetime.now().strftime('%Y-%m-%d')
    line=(
        Line(init_opts=options.InitOpts(theme=ThemeType.CHALK))
            .add_xaxis(x)
            .add_yaxis('红球', y1)
            .add_yaxis('蓝球', y2)
            .set_global_opts(title_opts=options.TitleOpts(title="最近{}期双色球红蓝球中奖次数".format(n),subtitle=tim))
    )
    line.render('双色球(折线图官方).html')

# 使用主题工具创建主题 https://echarts.baidu.com/theme-builder/
def mkLine2(x,y1,y2,n):
    register_files({'myTheme':['/js/customed.project','json']})
    tim = datetime.now().strftime('%Y-%m-%d')
    line=(
        # Line(init_opts=options.InitOpts(theme=ThemeType.WESTEROS))
        Line(init_opts=options.InitOpts(theme="myTheme"))
            .add_xaxis(x)
            .add_yaxis('红球', y1)
            .add_yaxis('蓝球', y2)
            .set_global_opts(title_opts=options.TitleOpts(title="最近{}期双色球红蓝球中奖次数".format(n),subtitle=tim))
    )
    line.render('双色球(折线图自定义).html')

def main(n):
    red_list = get_data(n)[0]
    blue_list = get_data(n)[1]
    x = sorted(set(red_list + blue_list))
    y_red = count_ball(x, red_list)
    y_blue = count_ball(x, blue_list)
    mkCharts(x, y_red, y_blue,n)  # 柱状图
    mkLine1(x,y_red,y_blue,n)   # 系统主题
    mkLine2(x,y_red,y_blue,n)  # 自定义主题

if __name__ == '__main__':
    n = input('您想获取最近多少期的数据？\n')
    main(n)
    print('统计信息已爬取完成。')